/**
 *
 * @Author 赵光
 * @Desc VelocityUtils
 * @Date 2020年5月11日
 */
package com.zlyx.easy.drools.util;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.KieBase;
import org.kie.api.io.ResourceType;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Velocity引擎渲染
 * 
 * @Author 赵光
 * @Desc VelocityUtils
 * @Date 2020年5月11日
 */
@Component
public class DroolsUtils {

	protected static Logger log = LoggerFactory.getLogger(DroolsUtils.class);

	private static final VelocityEngine ve = new VelocityEngine();

	static {
		ve.init();
	}

	/**
	 * 渲染规则模板(将属性值替换到规则模板)
	 *
	 * @param rule
	 * @param ruleName
	 * @param props
	 * @return
	 */
	public static String render(String rule, String ruleName, Map<String, String> props) {
		VelocityContext ctx = new VelocityContext();
		if (props != null) {
			props.forEach(ctx::put);
		}
		ctx.put("rule_name", ruleName);
		StringWriter sw = new StringWriter();
		ve.evaluate(ctx, sw, ruleName, rule);
		return sw.toString();
	}

	/**
	 * 初始化KieBase
	 * 
	 * @param rule
	 * @return
	 */
	public static KieBase initKieBase(String rule) {
		InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
		kbuilder.getErrors().forEach(error -> log.error(error.getMessage()));
		kbuilder.getKnowledgePackages()
				.forEach(knowledgePackage -> kBase.addPackage((InternalKnowledgePackage) knowledgePackage));
		return kBase;
	}

}
